package cn.itcast.contacts;

import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView rv_contact;
    private ContactAdapter adapter;
    private List<ContactInfo> contactInfos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        rv_contact = findViewById(R.id.rv_contacts);
        rv_contact.setLayoutManager(new LinearLayoutManager(this));
        getPermission();
    }

    String[] permissionList = new String[]{"android.permission.READ_CONTACTS"};

    public void getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> list = new ArrayList<>();
            for (String permission : permissionList) {
                if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    list.add(permission);
                }
            }
            if (list.size() > 0) {
                ActivityCompat.requestPermissions(this, list.toArray(new String[list.size()]), 1);
            } else {
                loadData();
            }
        } else {
            loadData();
        }
    }

    private void loadData() {
        contactInfos = getContacts();
        setData();
    }

    public void setData() {
        adapter = new ContactAdapter(this, contactInfos);
        rv_contact.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @SuppressLint("Range")
    public List<ContactInfo> getContacts() {
        List<ContactInfo> contactInfos = new ArrayList<>();
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        int hasPhoneNumberColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        int photoUriColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_URI); // 获取图片 URI 的列索引
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            int isHas = cursor.getInt(hasPhoneNumberColumnIndex);
            String photoUri = cursor.getString(photoUriColumnIndex); // 获取图片 URI
            if (isHas > 0) {
                Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
                while (phoneCursor.moveToNext()) {
                    ContactInfo info = new ContactInfo();
                    info.setContactName(name);
                    String number = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).trim();
                    number = number.replace(" ", "").replace("-", "").replace("(", "").replace(")", "");
                    info.setPhoneNumber(number);
                    info.setPhotoUri(photoUri); // 设置图片 URI
                    contactInfos.add(info);
                }
                phoneCursor.close();
            }
        }
        cursor.close();
        return contactInfos;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (permissions[i].equals("android.permission.READ_CONTACTS") && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    loadData();
                } else {
                    Toast.makeText(this, "权限申请失败，无法读取联系人信息", Toast.LENGTH_SHORT).show();
                    // 可能需要引导用户去设置中开启权限
                }
            }
        }
    }
}